package com.itany.corejava.code12_线程.zuoye;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月01日 9:09
 */
public class Test01 {
    public static void main(String[] args) {
        Odd odd=new Odd();
        odd.setName("奇数线程:");
        Even even=new Even();
        even.setName("偶数线程");
        odd.start();
        even.start();
    }
}

class Middle{
    public static boolean flag=true;
    public static Object object=new Object();

}
/**
 * 打印奇数
 */
class Odd extends Thread{
    private int i=1;

    @Override
    public void run() {
        while(true){
            synchronized (Middle.object){
                if(Middle.flag){
                    System.out.println(Thread.currentThread().getName()+"打印:"+i);
                    Middle.flag=false;
                    Middle.object.notifyAll();
                    if(i==99){
                        break;
                    }

                    i=i+2;
                }else{
                    try {
                        Middle.object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

/**
 * 打印偶数
 */
class Even extends Thread{
    private int i=2;
    @Override
    public void run() {
        synchronized (Middle.object){
            while(true){
                if(!Middle.flag){
                    System.out.println(Thread.currentThread().getName()+"打印:"+i);
                    if(i==100){
                        break;
                    }
                    Middle.flag=true;
                    i=i+2;
                    Middle.object.notifyAll();
                }else{
                    try {
                        Middle.object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}